# 功能： 指定目录使用clamavscan进行病毒扫描，查到病毒发送钉钉消息
# author： zhangyu
# time： 2021-06-10
# 安装： yum install clamav clamav-update -y
import requests
import time
import hashlib
import hmac
import base64
import re
import os
import socket

def clamavScan():
    cmdRes =  os.system("which freshclam")
    if cmdRes > 0 :
        print("clamav未发现，请确认是否安装，未安装执行yum install clamav clamav-update -y")
        exit
    elif cmdRes == 0:
        os.system('freshclam')
        dir = [
            "sbin",
            "bin",
            "usr/local",
            "home",
            "root",
            "tmp"
        ]
        Count = 0 
        for i in range(0,len(dir)-1):
            Cmd = "clamscan -ri /"+dir[i]+"/ | grep Infected| awk -F : '{print $2}'"       
            Infected_count = os.popen(Cmd).read().replace('\n', '').replace(' ', '')
            Count = Count + int(Infected_count)
    return Count

def SendMessage(message = ''):
    ### python3
    # secret：密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串，例如：SECxxxxxxxx
    secret = '{{ secret }}'
    # access_token：创建完钉钉机器人之后会自动生成，例如：access_tokenxxxx
    access_token = '{{ access_token }}'
    # timestamp：当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
    timestamp = int(round(time.time() * 1000))

    # 加密，获取sign和timestamp
    data = (str(timestamp) + '\n' + secret).encode('utf-8')
    secret = secret.encode('utf-8')
    signature = base64.b64encode(hmac.new(secret, data, digestmod=hashlib.sha256).digest())
    reg = re.compile(r"'(.*)'")
    signature = str(re.findall(reg,str(signature))[0])

    # 发送信息
    url = 'https://oapi.dingtalk.com/robot/send?access_token=%s&sign=%s&timestamp=%s' % (access_token,signature,timestamp)
    headers = {"Content-Type": "application/json ;charset=utf-8 "}
    try:
        response = requests.post(url, headers = headers, json = message, timeout = (3,60))
        print(response)
        response_msg = str(response.status_code) + ' ' + str(response.content)
        print(response_msg)
    except Exception as error_msg:
        print('error_msg==='+str(error_msg))
        response_msg = error_msg

    return response_msg

if __name__ == "__main__":
    Infected_count = clamavScan()
    IP=socket.gethostbyname(socket.gethostname())
    if Infected_count != 0:
        msg = {"msgtype":"text","text":{"content":"阿里云服务器%s扫描到%s个病毒，请登陆手动查杀"%(IP,Infected_count)},"at":{"isAtAll":False}}
        SendMessage(msg)